﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Collections.Generic;

using BizElements.TemplateEngine;

namespace BizElements.Generator
{
    public partial class CodeOptionsCtl : UserControl
    {
        public CodeOptionsCtl()
        {
            InitializeComponent();
        }

        #region Fields and properties.

        [Browsable(false)]
        public ITemplate[] TableItemTemplates
        {
            get { return this.uiEntityTemplateCollection.Templates; }
        }

        [Browsable(false)]
        public ITemplate SpAndCatalogTemplate
        {
            get { return this.uiSpAndCatalogTemplate.Template; }
        }

        IVariableValueBus variableBus;

        [Browsable(false)]
        public IVariableValueBus VariableBus
        {
            get { return this.variableBus; }
            set
            {
                this.variableBus = value;
                this.uiSpAndCatalogTemplate.VariableBus = value;
                this.uiEntityTemplateCollection.VariableBus = value;
            }
        }

        #endregion

        #region Project Settings.

        public void ReadProjectSettings(BizElementsSettings projectSettings)
        {
            this.uiSpAndCatalogTemplate.ReadSettings("SpAndCatalogTemplate", projectSettings);
            this.uiEntityTemplateCollection.ReadProjectSettings("TableTemplate", projectSettings);            

            SetupTableTemplatesLayout();
        }

        public void WriteProjectSettings(BizElementsSettings projectSettings)
        {
            this.uiEntityTemplateCollection.WriteProjectSettings("TableTemplate", projectSettings);
            this.uiSpAndCatalogTemplate.WriteSettings("SpAndCatalogTemplate", projectSettings);
        }

        #endregion

        private void uiEntityTemplateCollection_ControlAdded(object sender, ControlEventArgs e)
        {
            SetupTableTemplatesLayout();
        }

        private void uiEntityTemplateCollection_ControlRemoved(object sender, ControlEventArgs e)
        {
            SetupTableTemplatesLayout();
        }

        private void SetupTableTemplatesLayout()
        {
            Control lastChildControl = this.uiEntityTemplateCollection.Controls[this.uiEntityTemplateCollection.Controls.Count - 1];
            int xMargin = this.uiSpAndOtherPanels.Panel2.AutoScrollMargin.Width;
            int yMargin = lastChildControl.Bottom + 10;
            SuspendLayout();
            this.uiSpAndOtherPanels.Panel2.SetAutoScrollMargin(xMargin, yMargin);
            ResumeLayout();
        }

        public IList<TemplateComponentVariableDefinition> CreateComponentVariableDefinitionList()
        {
            return this.uiEntityTemplateCollection.CreateComponentVariableDefinitionList();
        }
    }
}
